package net.celisdelafuente.java.Acacia.pages;

import isbndb.BookLookup;
import isbndb.Request;
import isbndb.RequestType;
import isbndb.XmlResponseParser;
import isbndb.rest.RestRequestor;

import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.celisdelafuente.java.Acacia.entity.Author;
import net.celisdelafuente.java.Acacia.entity.Book;
import net.celisdelafuente.java.Acacia.entity.Classification;
import net.celisdelafuente.java.Acacia.entity.Publisher;
import net.celisdelafuente.java.Acacia.entity.Supplier;

import org.apache.click.control.ActionLink;
import org.apache.click.control.Column;
import org.apache.click.control.FieldSet;
import org.apache.click.control.Form;
import org.apache.click.control.HiddenField;
import org.apache.click.control.Option;
import org.apache.click.control.Select;
import org.apache.click.control.Submit;
import org.apache.click.control.Table;
import org.apache.click.control.TextArea;
import org.apache.click.control.TextField;
import org.apache.click.dataprovider.DataProvider;
import org.apache.click.extras.control.NumberField;

import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import com.openly.info.ISBN;
import com.openly.info.InvalidStandardIDException;

public class BooksPage extends BorderTemplate {
	
	private Form form = new Form("book");
	private FieldSet bFieldset = new FieldSet("Book");
	private Select pubDate = new Select("pubDate","Publishing Date");
	private Select edition = new Select("edition", "Edition");
	private Select status = new Select("status", "Status");
	private ArrayList<String> bookStatus = new ArrayList<String>();
	private Table table = new Table("books");
	private ActionLink editBook = new ActionLink("Edit", this,
			"onEditClick");
	private ActionLink deleteBook = new ActionLink("Delete", this,
			"onDeleteClick");

	public BooksPage() {
				
		pageTitle += " : Books";
		
		addControl(form);
		addControl(table);
		addControl(editBook);
		addControl(deleteBook);
		
		bFieldset.setColumns(2);
		form.add(bFieldset);
		
		HiddenField id = new HiddenField("id", Integer.class);
		TextField title = new TextField("title", "Title", true);
		bFieldset.add(title);
		NumberField retail_price = new NumberField("retail_price", 
				"Retail Price", true);
		bFieldset.add(retail_price);
		// Author
		TextField authorFullName = new TextField("authorFullName", "Author");
		bFieldset.add(authorFullName);
		NumberField isbn = new NumberField("isbn", "ISBN");
		bFieldset.add(isbn);
		NumberField quantity = new NumberField("quantity", "Qtty.");
		bFieldset.add(quantity);
		bFieldset.add(status);
		TextField subtitle = new TextField("subtitle", "Sub-title");
		bFieldset.add(subtitle);
		bFieldset.add(edition);
		bFieldset.add(pubDate);
		TextArea synopsis = new TextArea("synopsis", "Synopsis");
		synopsis.setCols(28);
		synopsis.setRows(3);
		bFieldset.add(synopsis);
		NumberField bulk_price = new NumberField("bulk_price", "Bulk Price");
		bFieldset.add(bulk_price);
		// Publisher
		TextField publisher = new TextField("publisher", "Publisher");
		bFieldset.add(publisher);
		TextField supplier = new TextField("supplier", "Supplier");
		bFieldset.add(supplier);
		// Classification
		TextField classKey = new TextField("classKey", "C. Key");
		bFieldset.add(classKey);
		TextField classDescription = new TextField("classDescription", "Classification");
		bFieldset.add(classDescription);
		
		bFieldset.add(new Submit("search", "  SEARCH  "));
		bFieldset.add(new Submit("ok",	"  ADD NEW  ", this, "onOkClick"));
		bFieldset.add(new Submit("cancel", "  CANCEL  ", this, "onCancelClick"));
		//bFieldset.add(new Submit("online", "  ON LINE SEARCH  ", this, "onOnlineClick"));
		
		table.setPageSize(10);
		table.setShowBanner(true);
		table.setSortable(true);
		table.addColumn(new Column("id"));
		table.addColumn(new Column("title"));
		//table.addColumn(new Column("authorFullName"));
		table.addColumn(new Column("quantity"));
		table.addColumn(new Column("retail_price"));
		
		deleteBook.setImageSrc("/images/user-trash.png");
        deleteBook.setTitle("Delete");
        deleteBook.setAttribute("onclick", 
        		"return window.confirm('Are you sure you want to delete this book?');");
        
        table.setDataProvider(new DataProvider<Book>() {
        	
			public List<Book> getData() {
        		List<Book> books = null;
        		try {
        			ConnectionSource connectionSource =
        					(JdbcConnectionSource) GetConnection();
        			books = book.queryForAll();
        			connectionSource.close();
        			return books;
        		} catch (SQLException e) {
        			e.printStackTrace();
        		}
        		return books;
        	}
		});
	}
	
	@Override
	public void onInit() {
		super.onInit();
		
		edition.setDefaultOption(Option.EMPTY_OPTION);
		for (int ed = 1; ed <= 30; ed++) {
			edition.add(ed);
		}
		pubDate.setDefaultOption(Option.EMPTY_OPTION);
		for (int y = 2012; y >= 1930; y-- ) {
				pubDate.add(new Option(y));
		}
		status.setDefaultOption(Option.EMPTY_OPTION);
		bookStatus.add("NEW");
		bookStatus.add("GOOD");
		bookStatus.add("POOR");
		bookStatus.add("BAD");
		status.addAll(bookStatus);				
	}
	
	@Override
	public void onRender() {
		super.onRender();
		
	}
	
	public boolean onOkClick() throws SQLException, ParseException {
		if(form.isValid()) {
			TextField fullName = (TextField)bFieldset.getControl("authorFullName");
			String[] fullNameArr = fullName.getValue().trim().split("[,]");
			TextField fPublisher = (TextField)bFieldset.getControl("publisher");
			TextField fIsbn = (TextField)bFieldset.getControl("isbn");
			Select fPubDate = (Select)bFieldset.getControl("pubDate");
			TextField fSupplier = (TextField)bFieldset.getControl("supplier");
			TextField fCkey = (TextField)bFieldset.getControl("classKey");
			TextField fClass = (TextField)bFieldset.getControl("classDescription");
			NumberField fQtty = (NumberField)bFieldset.getControl("quantity");
			
			ConnectionSource conn = (JdbcConnectionSource) GetConnection();
			
			Author a = new Author();
			if(fullNameArr.length > 1) {
				a = a.getByFullName(conn, author, fullNameArr);
				Integer author_id = a.getId();
				if (author_id != 0 && author_id != null) {
					if(fullNameArr.length > 2) {
						if (!a.getLname().equalsIgnoreCase(fullNameArr[1]) ||
								!a.getMname().equalsIgnoreCase(fullNameArr[2]) ||
								!a.getName().equalsIgnoreCase(fullNameArr[0]))
							author.update(a);
					} else if (fullNameArr.length == 2) {
						if (!a.getLname().equalsIgnoreCase(fullNameArr[1]) ||
								!a.getName().equalsIgnoreCase(fullNameArr[0]))
							author.update(a);
					}
					author.refresh(a);				
				} else {
					a = new Author(fullNameArr);
					author.create(a);
					author.refresh(a);
				}
			}
			
			Publisher p = new Publisher();
			if(!fPublisher.getValue().trim().isEmpty()) {
				p = p.getByName(conn, publisher, 
						fPublisher.getValue().trim());
				Integer publisher_id = p.getId();
				if(publisher_id != 0 && publisher_id != null) {
					if(!p.getName().equalsIgnoreCase(fPublisher.getValue().trim()))
						publisher.update(p);
					publisher.refresh(p);
				} else {
					p = new Publisher(fPublisher.getValue().trim());
					publisher.create(p);
					publisher.refresh(p);
				}
			}
			
			Supplier s = new Supplier();
			if(!fSupplier.getValue().isEmpty()) {
				s.getByName(conn, supplier, 
						fSupplier.getValue());
				Integer supplier_id = s.getId();
				if(supplier_id != 0 && supplier_id != null) {
					if(!s.getName().equalsIgnoreCase(fSupplier.getValue())) {
						supplier.update(s);
						supplier.refresh(s);
					}
				} else {
					s = new Supplier(fSupplier.getValue());
					supplier.create(s);
					supplier.refresh(s);
				}
			}
			
			Classification c = new Classification();
			if(!fCkey.getValue().isEmpty() && 
					!fClass.getValue().isEmpty()) {
				c.getByClassification(conn, classification, 
						fCkey.getValue(), fClass.getValue());
				Integer class_id = c.getId();
				if(class_id != 0 && class_id != null) {
					if(!c.getDescription().equalsIgnoreCase(fClass.getValue())) {
						classification.update(c);
					}
					if(!c.getCkey().equalsIgnoreCase(fCkey.getValue())) {
						classification.update(c);
					}
					classification.refresh(c);
				} else {
					c = new Classification(fCkey.getValue(), fClass.getValue());
					classification.create(c);
					classification.refresh(c);
				}
			}
			
			Book b = new Book();
			form.copyTo(b);
			try {
				ISBN validIsbn = new ISBN(fIsbn.getValue());
				b.setIsbn(validIsbn.toString());
			} catch (InvalidStandardIDException e) {
				// TODO Auto-generated catch block
				b.setIsbn("");
				e.printStackTrace();
			}
			DateFormat df = new SimpleDateFormat("yyyy");
			Date year = df.parse(fPubDate.getSelectedValues().get(0).toString());
			
			if(year != null)
				b.setPubdate(year);
			
			if(a != null)
				b.setAuthor(a);
			
			if(b != null)
				b.setPublisher(p);
			
			if(c != null)
				b.setClassification(c);
			
			if(fQtty.getValue().isEmpty())
				b.setQuantity(1);
			
			Integer book_id = b.getId();
			if (book_id != 0 && book_id != null) {
				book.update(b);
			} else {
				book.create(b);
			}
			
			conn.close();
			form.clearValues();
			String msg = "New book added succesfully";
			addModel("msg", msg);
		}
		return true;
	}
	
	public boolean onCancelClick() {
		setRedirect(HomePage.class);
		return false;
	}
	
	public boolean onOnlineClick() {
		
		TextField fullName = (TextField)bFieldset.getControl("authorFullName");
		String[] fullNameArr = fullName.getValue().trim().split("[,]");
		TextField fPublisher = (TextField)bFieldset.getControl("publisher");
		TextField fIsbn = (TextField)bFieldset.getControl("isbn");
		Select fPubDate = (Select)bFieldset.getControl("pubDate");
		TextField fSupplier = (TextField)bFieldset.getControl("supplier");
		TextField fCkey = (TextField)bFieldset.getControl("classKey");
		TextField fClass = (TextField)bFieldset.getControl("classDescription");

		BookLookup lookup = new BookLookup();
		
		Request request = new Request(getIsbnkey(), RequestType.ISBN, 
				fIsbn.getValue());
		
		RestRequestor restRequestor = new RestRequestor();
		restRequestor.request(request);
		
		XmlResponseParser xmlResponseParser = new XmlResponseParser();
		
		lookup.setAccessKey(getIsbnkey());
		lookup.setRequestor(restRequestor);
		lookup.setResponseParser(xmlResponseParser);
		
		isbndb.Book expectedBook = lookup.byIsbn(fIsbn.getValue());
		if(expectedBook != null)
			expectedBook.getTitle();
		
		
		/*
		ConnectionSource conn = (JdbcConnectionSource) GetConnection();
		
		Author a = new Author();
		if(fullNameArr.length > 1) {
			a = a.getByFullName(conn, author, fullNameArr);
			Integer author_id = a.getId();
			if (author_id != 0 && author_id != null) {
				if(fullNameArr.length > 2) {
					if (!a.getLname().equalsIgnoreCase(fullNameArr[1]) ||
							!a.getMname().equalsIgnoreCase(fullNameArr[2]) ||
							!a.getName().equalsIgnoreCase(fullNameArr[0]))
						author.update(a);
				} else if (fullNameArr.length == 2) {
					if (!a.getLname().equalsIgnoreCase(fullNameArr[1]) ||
							!a.getName().equalsIgnoreCase(fullNameArr[0]))
						author.update(a);
				}
				author.refresh(a);				
			} else {
				a = new Author(fullNameArr);
				author.create(a);
				author.refresh(a);
			}
		}
		
		Publisher p = new Publisher();
		if(!fPublisher.getValue().trim().isEmpty()) {
			p = p.getByName(conn, publisher, 
					fPublisher.getValue().trim());
			Integer publisher_id = p.getId();
			if(publisher_id != 0 && publisher_id != null) {
				if(!p.getName().equalsIgnoreCase(fPublisher.getValue().trim()))
					publisher.update(p);
				publisher.refresh(p);
			} else {
				p = new Publisher(fPublisher.getValue().trim());
				publisher.create(p);
				publisher.refresh(p);
			}
		}*/
		String msg = "No book found!";
		addModel("msg", msg);
		return true;
	}
	
	public boolean onSearchClick() {
		return true;
	}
	
}
